package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/loginByValidateCode")
    public Result loginByValidateCode(@RequestBody Map map,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {
        System.out.println(map.toString());

        //获取用户输入的电话号码
        String telephone = (String) map.get("telephone");

        //获取用户输入的验证码
        String validateCode = (String) map.get("validateCode");

        //获取redis中的验证码
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        //将用户输入的验证码与redis中的验证码进行对比
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {

            //如果数据库中没有当前会员则自动注册当前会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setPhoneNumber(telephone);
                try {
                    memberService.add(member);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            request.getSession().setAttribute("phoneNumber",telephone);

            Cookie cookie = new Cookie("telephone", telephone);
            cookie.setMaxAge(60*60*24);
            cookie.setPath("/");
            response.addCookie(cookie);

            return new Result(true, MessageConstant.LOGIN_SUCCESS,telephone);
        }

        return new Result(false, MessageConstant.VALIDATECODE_ERROR);

    }

}
